package com.jstyle.jclife.activity;

import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;

import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.blesdk.constant.DeviceKey;
import com.jstyle.blesdk.model.SportPeriod;
import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.MyWheelAdapter;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.Utils;
import com.jstyle.jclife.view.widget.views.WheelView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ActivityClockActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.button)
    Button button;

    @BindView(R.id.button2)
    Button button2;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.button6)
    Button button6;
    @BindView(R.id.button_starttime)
    Button buttonStarttime;
    @BindView(R.id.view_start)
    View viewStart;
    @BindView(R.id.button_end)
    Button buttonEnd;
    @BindView(R.id.button_endtime)
    Button buttonEndtime;
    @BindView(R.id.view_endtime)
    View viewEndtime;
    @BindView(R.id.button_8)
    Button button8;
    @BindView(R.id.button_interval)
    Button buttonInterval;
    @BindView(R.id.view_interval)
    View viewInterval;
    @BindView(R.id.button_9)
    Button button9;
    @BindView(R.id.button_step)
    TextView buttonStep;
    @BindView(R.id.view_step)
    View viewStep;
    @BindView(R.id.tv_week_title)
    TextView tvWeekTitle;
    @BindView(R.id.tv_week_content)
    TextView tvWeekContent;

    @BindArray(R.array.week)
    String[]weekArray;
    private static final String TAG = "ActivityClockActivity";
    private TimePickerDialog timePickerDialog;
    private int timeMode=0;
    private int [] weekPosition=new int[7];
    private AlertDialog weekDialog;
    private AlertDialog alertDialog;
    private AlertDialog intervalDialog;
    private AlertDialog stepDialog;
    private List<String>intervalList;
    private List<String>stepList;
    private MyWheelAdapter wheelAdapter;
    private WheelView wheelView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_activity);
        ButterKnife.bind(this);
        intervalList=getListData(1,30,9);
        stepList=getListData(1,50,6);
        sendData(SendCmdState.READ_SPORT_PERIOD);
        ScreenUtils.setTitleTypeface(button);
    }

    @OnClick({R.id.button_step,R.id.tv_week_title,R.id.iv_back, R.id.bt_activityclock_confim,R.id.button_starttime, R.id.button_endtime, R.id.button_interval,  R.id.tv_week_content})
    public void onViewClicked(View view) {
        if(Utils.isFastClick()){return;}
        switch (view.getId()) {
            case R.id.button_step:
                showStepDialog();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.button_starttime:
                timeMode=0;
                showTimeDialog();
                break;
            case R.id.button_endtime:
                timeMode=1;
                showTimeDialog();
                break;
            case R.id.button_interval:
                showIntervalDialog();
                break;
            case R.id.tv_week_content:
                showWeekDialog();
                break;
            case R.id.tv_week_title:
                showWeekDialog();
                break;
            case R.id.bt_activityclock_confim:
                setActivityClock();
                break;
        }
    }

    private void showStepDialog() {
        if(stepDialog==null){
            stepDialog=new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.Steps))
                    .setPositiveButton(getString(R.string.Confirm), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            int current = wheelView.getCurrentItem();
                            String currentInterval = stepList.get(current);
                            buttonStep.setText(currentInterval);
                        }
                    })
                    .setView(R.layout.dialog_activity_interval)
                    .setNegativeButton(getString(R.string.cancel), null)
                    .create();
        }
        stepDialog.show();
        wheelView=(WheelView)stepDialog.findViewById(R.id.WheelView_interval) ;
        wheelAdapter = new MyWheelAdapter(this, stepList, 0, 24, 14);
        wheelView.setViewAdapter(wheelAdapter);
        ScreenUtils.setDialogButtonTextColor(stepDialog);
    }

    private void showIntervalDialog() {
        if(intervalDialog==null){
            intervalDialog=new AlertDialog.Builder(this)
                    .setTitle(getString(R.string.Interval))
                    .setPositiveButton(getString(R.string.Confirm), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            int current = wheelView.getCurrentItem();
                            String currentInterval = intervalList.get(current);
                            buttonInterval.setText(currentInterval+getString(R.string.mins));
                        }
                    })
                    .setView(R.layout.dialog_activity_interval)
                    .setNegativeButton(getString(R.string.cancel), null)
                    .create();
        }
        intervalDialog.show();
        wheelView=(WheelView)intervalDialog.findViewById(R.id.WheelView_interval) ;
        wheelAdapter = new MyWheelAdapter(this, intervalList, 0, 24, 14);
        wheelView.setViewAdapter(wheelAdapter);
        ScreenUtils.setDialogButtonTextColor(intervalDialog);

    }
    private List<String> getListData(int start, int interval,int count) {
        List<String> list = new ArrayList<>();
        for (int i = start; i < count; i++) {
            list.add(String.valueOf(i*interval));
        }
        return list;
    }

    private void setActivityClock() {
        if(!BleManager.getInstance().isConnected()){
            showToast(getString(R.string.disonnected));
            return;
        }
        if(TextUtils.isEmpty(buttonStep.getText().toString()))return;
        buttonStep.setFocusable(false);
        String startTime=buttonStarttime.getText().toString();
        String endTime=buttonEndtime.getText().toString();
        int hourStart = Integer.parseInt(startTime.split(":")[0]);
        int minStart = Integer.parseInt(startTime.split(":")[1]);
        int hourEnd = Integer.parseInt(endTime.split(":")[0]);
        int minEnd = Integer.parseInt(endTime.split(":")[1]);
        int minInterval = Integer.parseInt(buttonInterval.getText().toString().split(getString(R.string.mins))[0]);
        int minStep = Integer.parseInt(buttonStep.getText().toString());
        int week = 0;
        for (int  i =0;i<7;i++) {
            if(weekPosition[i]==1)
                week += Math.pow(2, i);
        }
        SportPeriod sportPeriod = new SportPeriod();
        sportPeriod.setStartHour(hourStart);
        sportPeriod.setStartMinute(minStart);
        sportPeriod.setEndHour(hourEnd);
        sportPeriod.setEndMinute(minEnd);
        sportPeriod.setIntervalTime(minInterval);
        sportPeriod.setLeastStep(minStep);
        sportPeriod.setWeek(week);
        sportPeriod.setEnable(true);
        sendData(SendCmdState.SET_SPORT_PERIOD, sportPeriod);
        ScreenUtils.showSetSuccessFul(buttonStep);

    }
    private void showWeekDialog() {
        boolean[]checked=new boolean[7];
        for(int i=0;i<7;i++){
            checked[i]=weekPosition[i]==1;
        }
        weekDialog=new AlertDialog.Builder(this)
                .setMultiChoiceItems(weekArray,checked, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        weekPosition[which]=isChecked?1:0;
                    }
                })
                .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       showWeekText();
                    }
                }).setNegativeButton(getString(R.string.cancel),null).create();
        weekDialog.show();
        ScreenUtils.setDialogButtonTextColor(weekDialog);
    }

    private void showWeekText(){
        StringBuffer stringBuffer=new StringBuffer();
        for(int i=0;i<weekPosition.length;i++){
            if(weekPosition[i]==1){
                stringBuffer.append(weekArray[i]).append(", ");
            }
        }
        String weekString=stringBuffer.toString().trim();
        if(!TextUtils.isEmpty(weekString)){
            weekString= weekString.substring(0,weekString.length()-1);
        }
        tvWeekContent.setText(weekString);
    }
    private void showTimeDialog() {

        String text=timeMode==0?buttonStarttime.getText().toString():buttonEndtime.getText().toString();
        int hour=0;
        int min=0;
        if(!TextUtils.isEmpty(text)){
            hour=Integer.valueOf(text.split(":")[0]);
            min=Integer.valueOf(text.split(":")[1]);
        }
        timePickerDialog=new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    String time=String.format("%1$02d:%2$02d",hourOfDay,minute);
                    if(timeMode==0){
                        buttonStarttime.setText(time);
                    }else{
                        buttonEndtime.setText(time);
                    }
                    Log.i(TAG, "onTimeSet: "+hourOfDay+" "+minute);
                }
            },hour,min,true);
        timePickerDialog.show();
        ScreenUtils.setButtonTextColor(timePickerDialog);
    }

    @Override
    public void dataCallback(Map<String, String> maps, SendCmdState sendCmdState) {
        super.dataCallback(maps, sendCmdState);
        switch (sendCmdState){
            case READ_SPORT_PERIOD:
                int startHour = Integer.valueOf(maps.get(DeviceKey.KSportStartHour));
                int startMin = Integer.valueOf(maps.get(DeviceKey.KSportStartMinter));
                int endHour = Integer.valueOf(maps.get(DeviceKey.KSportEndHour));
                int endMin = Integer.valueOf(maps.get(DeviceKey.KSportEndMinter));
                String timeInterval = maps.get(DeviceKey.KSportNotifierTime);
                String week = maps.get(DeviceKey.KSportWeekEnable);
                String step = maps.get(DeviceKey.KSportMinStep);
                String[]weekStrings=week.split("-");
                for(int i=0;i<7;i++){
                    int position=Integer.valueOf(weekStrings[i]);
                    weekPosition[i]=position;
                }
                buttonStarttime.setText(String.format("%1$02d:%2$02d",startHour,startMin));
                buttonEndtime.setText(String.format("%1$02d:%2$02d",endHour,endMin));
                buttonInterval.setText(timeInterval+getString(R.string.mins));
                buttonStep.setText(step);
                showWeekText();
                break;
        }
    }
}
